package com.codeoss.framework.util;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlUtil {
	public static Document getDocumentByInputStream(InputStream is) throws Exception {
		DocumentBuilderFactory viewFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = viewFactory.newDocumentBuilder();
		Document document = builder.parse(is);
		return document;
	}
	
	public static Document createDocument() {
		DocumentBuilderFactory viewFactory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = viewFactory.newDocumentBuilder();
			return builder.newDocument();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	public static String convertXmlElementToString(Element element) {
		try {
			DocumentBuilderFactory viewFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = viewFactory.newDocumentBuilder();
			Document document = builder.newDocument();
			Element newElement=(Element)document.importNode(element, true);
			document.appendChild(newElement);
			 TransformerFactory transFactory = TransformerFactory.newInstance();
			 Transformer transformer= transFactory.newTransformer();
			 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			 StringWriter buffer = new StringWriter();
			 transformer.transform(new DOMSource(document),new StreamResult(buffer));
			 return buffer.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
